package cn.schoolwow.quickserver.handler;

import cn.schoolwow.quickserver.domain.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 打印请求响应日志
 * */
public class RequestResponseLogHandler implements Handler {
    private static Logger logger = LoggerFactory.getLogger(RequestResponseLogHandler.class);

    @Override
    public Handler handle(Client client) throws Exception {
        logger.debug("[请求与响应]\n{}", getRequestAndResponseLog(client));
        return new KeepAliveHandler();
    }

    /**
     * 获取请求和响应日志
     */
    private String getRequestAndResponseLog(Client client) {
        StringBuilder contentBuilder = new StringBuilder("====================================================================\n");
        contentBuilder.append(client.httpRequestMeta.statusLine + "\n");
        Set<Map.Entry<String, List<String>>> requestHeaderSet = client.httpRequestMeta.headers.entrySet();
        for (Map.Entry<String, List<String>> entry : requestHeaderSet) {
            for(String value : entry.getValue()){
                contentBuilder.append(entry.getKey() + ": " + value + "\n");
            }
        }
        if(null!=client.httpRequestMeta.body){
            if(client.httpRequestMeta.fileParameterMap.size()>0){
                contentBuilder.append("\n" + client.httpRequestMeta.fileParameterMap + "\n\n");
            }else{
                contentBuilder.append("\n" + client.httpRequestMeta.body + "\n\n");
            }
        }else if(null!=client.httpRequestMeta.bodyBytes&&client.httpRequestMeta.bodyBytes.length>0){
            contentBuilder.append("\n{" + client.httpRequestMeta.bodyBytes.length + "}\n\n");
        }else{
            contentBuilder.append("\n");
        }

        contentBuilder.append(client.httpResponseMeta.protocol + " " + client.httpResponseMeta.status + " " + client.httpResponseMeta.statusMessage + "\n");
        Set<Map.Entry<String, List<String>>> responseHeaderSet = client.httpResponseMeta.headers.entrySet();
        for (Map.Entry<String, List<String>> entry : responseHeaderSet) {
            for(String value : entry.getValue()){
                contentBuilder.append(entry.getKey() + ": " + value + "\n");
            }
        }
        if(client.httpResponseMeta.contentLength>0){
            if(null==client.httpResponseMeta.result){
                contentBuilder.append("\n[" + client.httpResponseMeta.contentLength + "]");
            }else{
                contentBuilder.append("\n" + client.httpResponseMeta.result);
            }
        }else{
            contentBuilder.append("\n");
        }
        contentBuilder.append("\n====================================================================\n");
        return contentBuilder.toString();
    }
}
